
//
//  MJPictureSelectController.swift
//  新浪微博
//
//  Created by MaJi on 16/4/19.
//  Copyright © 2016年 MaJi. All rights reserved.
//

import UIKit
import HMImagePicker
private let rowCount = 4
private let margin:CGFloat = 3
//最多可以上传多少张图片
let maxImageCount = 9
//每个item的宽度
private let itemW:CGFloat = (screenWidth - CGFloat(rowCount+1) * margin)/CGFloat(rowCount)
private let pictureSelectCell = "pictureSelectCell"

class MJPictureSelectController: UICollectionViewController {
    
    //    保存添加的图片的数组
    lazy var imageList = [UIImage]()
//    记录选中的图片的数组
    private var selectedAssets:[PHAsset]?
    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView!.backgroundColor = UIColor.clearColor()
        
        //        注册cell
        self.collectionView!.registerClass(MJPictureCell.self, forCellWithReuseIdentifier: pictureSelectCell)
        
    }
    //    override init(collectionViewLayout layout: UICollectionViewLayout) {
    //        let FlowLayout = UICollectionViewFlowLayout()
    //        super.init(collectionViewLayout: FlowLayout)
    //    }
    init(){
        let FlowLayout = UICollectionViewFlowLayout()
        super.init(collectionViewLayout: FlowLayout)
        FlowLayout.itemSize = CGSize(width: itemW, height: itemW)
        FlowLayout.minimumInteritemSpacing = 0
        FlowLayout.minimumLineSpacing = 0
        FlowLayout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: 0, right: margin)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK: UICollectionViewDataSource
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let detla = imageList.count >= maxImageCount ? 0 : 1
        return imageList.count + detla
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureSelectCell, forIndexPath: indexPath) as! MJPictureCell
        cell.backgroundColor = randomColor()
        cell.delegate = self
        //        添加图片
        if imageList.count == indexPath.row {
//            cell.deleteBtn.hidden = true
// //        解决重用的问题
//            cell.composeBtn.setImage(nil, forState: .Normal)
            cell.image = nil
        }else{
//            cell.composeBtn.setImage(imageList[indexPath.row], forState: .Normal)
//            cell.deleteBtn.hidden = false
            cell.image = imageList[indexPath.row]
        }
        return cell
    }
    
}

//控制器实现代理方法
extension MJPictureSelectController:MJPictureCellDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    //    实现代理方法
    //    图片选择控制器.跳转到相册
    func userWillChoosePicture() {
        print("vc choose")
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
            let picker = HMImagePickerController(selectedAssets: selectedAssets)
            picker.maxPickerCount = maxImageCount
            picker.targetSize = CGSize(width: 600, height: 600)
            picker.pickerDelegate = self
            presentViewController(picker, animated: true, completion: nil)
        
        }
//        用系统提供的方法,一次只能选择一张图片
//        //判断相册是否可用(在使用模拟器时摄像头是不能用的),模拟器上摄像头不可用
//        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
//            
//            let pickVC = UIImagePickerController()
//            presentViewController(pickVC, animated: true, completion: nil)
//            //            设置代理
//            pickVC.delegate = self
//        }
    }
    
    //    在删除按钮方法里添加一个cell,为了获得用户点击的是哪个cell
    func userWillDeletePicture(cell: MJPictureCell) {
        //1.获取用户点击的是哪一个cell
        //通过协议方法的参数获取用户点击的cell
        //2.获取cell对应的indexPath
        if let indexPath = collectionView?.indexPathForCell(cell) {
            //3.在数组中移除对应 indexPath.item 对应的元素
            imageList.removeAtIndex(indexPath.item)
//            3.1移除上一次记录的选择源
            selectedAssets?.removeAtIndex(indexPath.item)
            //刷新数据
            collectionView?.reloadData()
        }
    }
    
    //    func userWillDeletePicture(cell:MJPictureCell) {
    //        if let indexPath = collectionView?.indexPathForCell(cell) {
    //
    //            self.imageList.removeAtIndex((indexPath.item))
    //        }
    //        self.collectionView?.reloadData()
    //    }
    //    实现图片控制器的方法
    //一旦实现了协议方法之后 图片选择器的消失 就交给程序员来管理
//    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
//        //        print(image)
//        //        保存图片
//        imageList.append(image)
//        //        刷新cell
//        self.collectionView?.reloadData()
//        dismissViewControllerAnimated(true, completion: nil)
//        //
//    }
    
}
extension MJPictureSelectController:HMImagePickerControllerDelegate{
    func imagePickerController(picker: HMImagePickerController, didFinishSelectedImages images: [UIImage], selectedAssets: [PHAsset]?) {
        self.imageList = images
        self.selectedAssets = selectedAssets
        self.collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
    }
}
//定义协议 让按钮的点击事件传递到控制器
@objc protocol MJPictureCellDelegate:NSObjectProtocol{
    optional func userWillChoosePicture()
    optional func userWillDeletePicture(cell:MJPictureCell)
}

//自定义cell添加两个按钮
class MJPictureCell:UICollectionViewCell{
//    代理对象用weak
    weak var delegate:MJPictureCellDelegate?
    var image:UIImage? {
        didSet{
            deleteBtn.hidden = (image==nil)
            composeBtn.setImage(image, forState: .Normal)
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupUI(){
        contentView.addSubview(composeBtn)
        contentView.addSubview(deleteBtn)
        //        给按钮添加点击事件
        composeBtn.addTarget(self, action: "choosePicture", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deletePicture", forControlEvents: .TouchUpInside)
        //        设置自动布局
        composeBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView)
        }
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.right.top.equalTo(composeBtn)
        }
    }
    @objc private func choosePicture(){
        print("选择图片")
        if image != nil{
            print("已经有图片啦")
            return
        }
        self.delegate?.userWillChoosePicture?()
        
    }
    @objc private func deletePicture(){
        print("删除图片")
        composeBtn.setImage(nil, forState: .Normal)
        delegate?.userWillDeletePicture?(self)
    }
    //    懒加载子控件
    private lazy var composeBtn:UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: .Normal)
        btn.setBackgroundImage(UIImage(named: "compose_pic_add_highlighted"), forState: .Highlighted)
        return btn
    }()
    private lazy var deleteBtn: UIButton = {
        let btn = UIButton()
        btn.setBackgroundImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        return btn
    }()
}
